<?php

declare(strict_types=1);
/**
 * This file is part of bearing-web.
 *
 * @link     https://www.bearing.cn/
 * @contact  tech@bearing.cn
 * @license  https://gitee.com/cppo/bearing_web/-/blob/master/README.md
 */

namespace frontend\actions;

use common\models\OrderItemModel;
use common\models\OrderModel;
use yii\rest\ViewAction;
use yii\web\NotFoundHttpException;

class OrderViewAction extends ViewAction
{
    /**
     * @throws NotFoundHttpException
     */
    public function run($id): array
    {
        $model = $this->findModel($id);
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id, $model);
        }
        if (! $model instanceof OrderModel || ! $model->id) {
            return [];
        }
        return [
            'id' => $model->id,
            'status' => $model->status,
            'create_time' => $model->create_time,
            'items' => $this->getOrderItems($model->id),
            'price' => floatval($model->price),
            'shipping' => floatval($model->shipping),
            'tax' => floatval($model->tax),
            'total' => floatval(bcadd(bcadd(strval($model->tax), strval($model->shipping), 2), strval($model->price), 2)),
            'shippingAddress' => json_decode($model->address, true),
        ];
    }

    private function getOrderItems(int $orderId = 0): array
    {
        $products = [];
        if (! $orderId) {
            return $products;
        }
        $items = OrderItemModel::findAll(['order_id' => $orderId]);
        if (! count($items)) {
            return $products;
        }
        foreach ($items as $key => $item) {
            $products[$key] = [
                'product' => json_decode($item->attr, true),
                'quantity' => $item->num,
            ];
        }
        return $products;
    }
}
